//
//  Apputil.m
//  DaDaImage-iPad2.0
//
//  Created by dengchunhua on 16/7/1.
//  Copyright © 2016年 iinda.com. All rights reserved.
//

#import "Apputil.h"
#import "SVProgressHUD.h"
#import "AppDelegate.h"

#define LocalizedString(key) [Apputil LocalizedString:key]
//---------------------正则表达式--------------------------//
#define _FORM_STRING_NUMBER__ @"^[0-9]+([.]{0,1}[0-9]{0,2}){0,1}$"
#define _FORM_STRING_EMAIL__ @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}"
#define USERDEFAULT [NSUserDefaults standardUserDefaults]

@interface Apputil ()


@end

@implementation Apputil

+(NSString *)LocalizedString:(NSString *)str
{
    return NSLocalizedString(str, @"");
}

+ (void)showMessage:(NSString *)message afterDelay:(NSTimeInterval)time
{
    
    [SVProgressHUD showProgress:1 status:message];
    [SVProgressHUD performSelector:@selector(dismiss) withObject:nil afterDelay:time? time : 0.5];
}

+ (void)showError:(id)errorMessage {
    if([errorMessage isKindOfClass:[NSError class]])
    {
//        [SVProgressHUD showImage:nil status:LocalizedString([errorMessage localizedDescription])];
        [SVProgressHUD showErrorWithStatus:LocalizedString([errorMessage localizedDescription])];
        [SVProgressHUD performSelector:@selector(dismiss) withObject:nil afterDelay:1.0];
//        [SVProgressHUD showProgress:1 status:LocalizedString([errorMessage localizedDescription])];
//        [SVProgressHUD performSelector:@selector(dismiss) withObject:nil afterDelay:1.0];
    }else{
//            //延迟一定的时间触发事件（延迟提交）
//            dispatch_time_t delayTime = dispatch_time(DISPATCH_TIME_NOW, 1.0*NSEC_PER_SEC);
//            dispatch_after(delayTime, dispatch_get_main_queue(), ^{
//                [(AppDelegate *)[UIApplication sharedApplication].delegate showWindowHome:LOGIN_OUT];
//            });
//            [SVProgressHUD showImage:nil status:errorMessage];
        [SVProgressHUD showErrorWithStatus:errorMessage];
    }
   
    [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeNone];
    [SVProgressHUD performSelector:@selector(dismiss) withObject:nil afterDelay:1.0];
}

+ (void)showMessage:(NSString*) message {
    [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeClear];
    [SVProgressHUD showWithStatus: message ? message : LocalizedString(@"Loading")];
}

+ (void)dismiss
{
    [SVProgressHUD dismiss];
}

+(void)NSUserDefAddString:(NSString *)obj key:(NSString *)key
{
    [[NSUserDefaults standardUserDefaults] setObject:obj forKey:key];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

+(void)NSUserDefAddOject:(id)obj key:(NSString *)key
{
    [[NSUserDefaults standardUserDefaults] setObject:obj forKey:key];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

+(id) QueryNSUserDefToKey:(NSString *)key
{
    NSString* value = [[NSUserDefaults standardUserDefaults] objectForKey:key];
    [[NSUserDefaults standardUserDefaults] synchronize];
    return value;
}

//+ (void)ReleaseServiceNotice:(NSDictionary *)notifiDict noticeName:(NSString *)name
//{
//    if ([Apputil checkNewWorkStatus]) {
//        [[NSNotificationCenter defaultCenter] postNotificationName:name object:notifiDict];
//    }else{
//        [Apputil showError:@"没有网络"];
//    }
//}

+ (BOOL)validateEmailString:(NSString *)emailStr
{
//    BOOL stricterFilter = NO;
//    NSString *stricterFilterString = @"[A-Z0-9a-z\\._%+-]+@([A-Za-z0-9-]+\\.)+[A-Za-z]{2,4}";
//    NSString *laxString = @".+@([A-Za-z0-9-]+\\.)+[A-Za-z]{2}[A-Za-z]*";
//    NSString *emailRegex = stricterFilter ? stricterFilterString : laxString;
//    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
//    return [emailTest evaluateWithObject:emailStr];
    //去掉字符串左右两边空格
    emailStr = [emailStr stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    BOOL bl = [[NSPredicate predicateWithFormat:@"SELF MATCHES %@",_FORM_STRING_EMAIL__] evaluateWithObject:emailStr];
    return bl;
}

+ (BOOL)validatePhoneWithString:(NSString *)phoneNumber
{
//    NSString *phoneRegex = @"^[0-9]{6,14}$";
//    NSPredicate *phoneTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", phoneRegex];
    
//    return [phoneTest evaluateWithObject:phoneNumber];
    
    if (phoneNumber.length != 11)
    {
        return NO;
    }
    /**
     * 手机号码:
     * 13[0-9], 14[5,7], 15[0, 1, 2, 3, 5, 6, 7, 8, 9], 17[6, 7, 8], 18[0-9], 170[0-9]
     * 移动号段: 134,135,136,137,138,139,150,151,152,157,158,159,182,183,184,187,188,147,178,1705
     * 联通号段: 130,131,132,155,156,185,186,145,176,1709
     * 电信号段: 133,153,180,181,189,177,1700
     */
    NSString *MOBILE = @"^1((3[0-9]|4[57]|5[0-35-9]|7[0678]|8[0-9])\\d{8}$)";
    /**
     * 中国移动：China Mobile
     * 134,135,136,137,138,139,150,151,152,157,158,159,182,183,184,187,188,147,178,1705
     */
    NSString *CM = @"(^1(3[4-9]|4[7]|5[0-27-9]|7[8]|8[2-478])\\d{8}$)|(^1705\\d{7}$)";
    /**
     * 中国联通：China Unicom
     * 130,131,132,155,156,185,186,145,176,1709
     */
    NSString *CU = @"(^1(3[0-2]|4[5]|5[56]|7[6]|8[56])\\d{8}$)|(^1709\\d{7}$)";
    /**
     * 中国电信：China Telecom
     * 133,153,180,181,189,177,1700
     */
    NSString *CT = @"(^1(33|53|7[37]|8[019])\\d{8}$)|(^1700\\d{7}$)";
    
    
    NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", MOBILE];
    NSPredicate *regextestcm = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CM];
    NSPredicate *regextestcu = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CU];
    NSPredicate *regextestct = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CT];
    
    if (([regextestmobile evaluateWithObject:phoneNumber] == YES)
        || ([regextestcm evaluateWithObject:phoneNumber] == YES)
        || ([regextestct evaluateWithObject:phoneNumber] == YES)
        || ([regextestcu evaluateWithObject:phoneNumber] == YES))
    {
        return YES;
    }
    else
    {
        return NO;
    }
    
}

+ (NSString *)getconvertUrlStr:(NSString *)originUrlStr
{
    NSString *urlstr = [originUrlStr stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet characterSetWithCharactersInString:@"`#%^{}\"[]|\\<> "].invertedSet];
    NSString *urls = [urlstr substringFromIndex:3];
    return urls;
}

+ (NSString *)getfilePathWithUrlStr:(NSString *)urlStr docname:(NSString *)docname
{
    NSURL *url = [NSURL URLWithString:[Apputil getconvertUrlStr:urlStr]];
    NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:url];
    request.HTTPMethod = @"HEAD";
    NSURLResponse* response = nil;
    [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:NULL];
    //获取服务器的文件信息
    NSString *docoriginName = response.suggestedFilename;
    NSArray *pathArr = [docoriginName componentsSeparatedByString:@"."];
    NSString *pathname = [NSString stringWithFormat:@"%@.%@",docname,[pathArr lastObject]];
    NSString *filePath = [NSTemporaryDirectory() stringByAppendingPathComponent:pathname];
    return filePath;
}

+(NSString *)distanceWithMetre:(long)metre {
    NSString * distanceStr;
    if (metre < 1000.0) {
        distanceStr = [NSString stringWithFormat:@"%ldm",metre];
    }else if (metre > 1000.0) {
        long km = metre / 1000.0 ;
        long decimals = (metre % 1000) / 100.0 ;
        distanceStr = [NSString stringWithFormat:@"%ld.%ldKm",km,decimals];
        if (km > 200) {
            distanceStr = @"";
        }
    }
    return distanceStr;
}


+(NSURL *)getUrlByImagePath:(NSString *)path size:(MBImageSizeCode)size
{
    if ([path containsString:@"@"]) {
        return [NSURL URLWithString:path];
    }
    
    //
    //    typedef enum {
    //        MBImageSize70x70 ,
    //        MBImageSize160x160,// = 1,
    //        MBImageSize240x240,// = 2,
    //        MBImageSize500x0,// = 3,
    //        MBImageSize640x0,// = 4
    //        MBImageSize640x640,// = 5
    //        MBImageSize640x480,// = 5
    //    } MBImageSizeCode;
    
    NSArray *sizeCodeArray=@[
                             @"@70w_70h_1c_1e_90Q",
                             @"@160w_160h_1c_1e_90Q",
                             @"@240w_240h_1c_1e_90Q",
                             @"@500w_4000h_90Q",
                             @"@640w_4000h_90Q",
                             @"@640w_640h_90Q",
                             @"@640w_480h_1c_1e_90Q",
                             @"@50w_50h",
                             ];
    NSString *postfix=@".jpg";
    if(path.length>=4)
    {
        postfix=[path substringFromIndex:path.length -4];
    }
    if(![postfix isEqualToString:@".jpg"]&&![postfix isEqualToString:@".png"])
    {
        postfix=@".jpg";
    }
    NSString *urlString=[NSString stringWithFormat:@"%@%@%@",[path stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],[sizeCodeArray objectAtIndex:size],postfix ];
    NSURL *imageUrl=[NSURL URLWithString:urlString];
    
    return imageUrl;
}

+ (void)showView:(UIView *)view center:(CGPoint)point frame:(CGRect)rect completion:(void (^)(BOOL bSuccess))completion{
    view.center        = point;
    view.transform     = CGAffineTransformMakeRotation(-M_1_PI / 2);
    
    [UIView animateWithDuration:0.3f delay:0.0 options:UIViewAnimationOptionCurveEaseIn animations:^{
        view.transform = CGAffineTransformMakeRotation(0);
        view.frame     = rect;
    } completion:^(BOOL finished) {
        completion(finished);
    }];
}

+ (void)dismissView:(UIView *)view center:(CGPoint)point completion:(void (^)(BOOL bSuccess))completion{
    [UIView animateWithDuration:0.6f delay:0.0 options:UIViewAnimationOptionCurveEaseOut animations:^{
        view.center    = point;
        view.transform = CGAffineTransformMakeRotation(M_1_PI / 1.5);
    } completion:^(BOOL finished) {
        completion(finished);
    }];
}

+(UIViewController *)dch_viewControllerOfView:(UIView *)theView
{
    for (UIView *view = theView; view; view = view.superview)
    {
        UIResponder *nextResponder = [view nextResponder];
        if ([nextResponder isKindOfClass:[UIViewController class]])
        {
            return (UIViewController *)nextResponder;
        }
    }
    return nil;
}


+ (NSString *)getTime:(NSString *)datestr
{
    //    NSTimeInterval late = (long)[item.regtime doubleValue];
    //    //时间戳转换为时间
    //    NSDate *lateDate = [NSDate dateWithTimeIntervalSince1970:late];
    // 实例化一个NSDateFommater对象
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"]];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSDate *updateDate = [dateFormatter dateFromString:datestr];
    //    [dateFormatter setDateFormat:@""];
    
    NSString *lateDateStr = [dateFormatter stringFromDate:updateDate];
    //    NSDate *d = [dateFormatter dateFromString:lateDateStr];
    //日期转换成时间戳
    NSTimeInterval dateTime = [updateDate timeIntervalSince1970]*1;
    
    
    NSTimeInterval now = [[NSDate date] timeIntervalSince1970]*1;
    
    NSString *timeString = nil;
    
    //时间差
    NSTimeInterval cha = now - dateTime;
    if (cha/3600<1) {
        timeString = [NSString stringWithFormat:@"%f", cha/60];
        timeString = [timeString substringToIndex:timeString.length-7];
        timeString= [timeString intValue]==0?@"刚刚":[NSString stringWithFormat:@"%@分钟前", timeString];
    }
    if (cha/3600>1&&cha/86400<1) {
        timeString = [NSString stringWithFormat:@"%f", cha/3600];
        timeString = [timeString substringToIndex:timeString.length-7];
        timeString=[NSString stringWithFormat:@"%@小时前", timeString];
    }
    if (cha/86400>1&&cha/86400<=5)
    {
        timeString = [NSString stringWithFormat:@"%f", cha/86400];
        timeString = [timeString substringToIndex:timeString.length-7];
        timeString=[NSString stringWithFormat:@"%@天前", timeString];
    }
    if (cha/86400>5) {
        timeString = lateDateStr;
    }
    return timeString;
}

//+ (NSString *)getDayWithDateStr:(NSString *)datestr
//{
//    NSDate *targetDate = [NSDate dateWithString:datestr format:@"yyyy-MM-dd HH:mm:ss"];
//    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
//    [dateFormatter setDateFormat:@"dd日"];
//    NSString *daystr = [dateFormatter stringFromDate:targetDate];
//    return daystr;
//}
//
//+ (NSString *)getTimeWithDateStr:(NSString *)datestr
//{
//    NSDate *targetDate = [NSDate dateWithString:datestr format:@"yyyy-MM-dd HH:mm:ss"];
//    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
//    [dateFormatter setDateFormat:@"HH:mm"];
//    NSString *timeStr = [dateFormatter stringFromDate:targetDate];
//    return timeStr;
//}
//
//+ (NSString *)getDateWithDateStr:(NSString *)datestr
//{
//    NSDate *targetDate = [NSDate dateWithString:datestr format:@"yyyy-MM-dd HH:mm:ss"];
//    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
//    [dateFormatter setDateFormat:@"yyyy年MM月dd日"];
//    NSString *dateStr = [dateFormatter stringFromDate:targetDate];
//   // NSString *dateStr = [dateFormatter stringFromDate:updateDate];
//    return dateStr;
//}


#pragma make baidu map poi
+ (double)bdlon:(double)gg_lat gg_lon:(double)gg_lon{
    double x_pi = 3.14159265358979324 * 3000.0 / 180.0;
    double x = gg_lon, y = gg_lat;
    double z = sqrt(x * x + y * y) + 0.00002 * sin(y * x_pi);
    double theta = atan2(y, x) + 0.000003 * cos(x * x_pi);
    return z * cos(theta) + 0.0065;
}

+ (double)bdlat:(double)gg_lat gg_lon:(double)gg_lon{
    double x_pi = 3.14159265358979324 * 3000.0 / 180.0;
    double x = gg_lon, y = gg_lat;
    double z = sqrt(x * x + y * y) + 0.00002 * sin(y * x_pi);
    double theta = atan2(y, x) + 0.000003 * cos(x * x_pi);
    return z * sin(theta) + 0.006;
}

//获取文件的信息
-(NSString *)getServerFileInfo:(NSURL*)url docname:(NSString *)docname {
    NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:url];
    request.HTTPMethod = @"HEAD";
    NSURLResponse* response = nil;
    [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:NULL];
    //获取服务器的文件信息
//    self.expectedContentLength = response.expectedContentLength;
    NSString *docoriginName = response.suggestedFilename;
    NSArray *pathArr = [docoriginName componentsSeparatedByString:@"."];
    NSString *pathname = [NSString stringWithFormat:@"%@.%@",docname,[pathArr lastObject]];
    NSString *filePath = [NSTemporaryDirectory() stringByAppendingPathComponent:pathname];
    return filePath;
}

#pragma mark - 根据文字计算高度
//uitextview
+ (CGFloat)textHeight:(NSString *)s font:(UIFont*)font textWidth:(CGFloat)width{
    if (!s || s.length <= 0 || !font) {
        return 0;
    }
    
    CGSize constraint = CGSizeMake(width, CGFLOAT_MAX);
    CGSize size = CGSizeZero;
    NSDictionary *attribute = @{NSFontAttributeName:font};
    size = [s boundingRectWithSize:constraint options: NSStringDrawingTruncatesLastVisibleLine | NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:attribute context:nil].size;
    
    float fHeight     = size.height;
    return ceil(fHeight);
}

+ (CGFloat)textWidth:(NSString *)s font:(UIFont*)font textHeight:(CGFloat)height{
    if (!s || s.length <= 0 || !font) {
        return 0;
    }
    CGSize constraint = CGSizeMake(CGFLOAT_MAX, height);
    CGSize size = CGSizeZero;
    NSDictionary *attribute = @{NSFontAttributeName:font};
    size = [s boundingRectWithSize:constraint options: NSStringDrawingTruncatesLastVisibleLine | NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:attribute context:nil].size;
    float fwidth = size.width;
    return ceil(fwidth);
}

//uilabel
+ (CGFloat)textHeight:(NSString *)s fontName:(NSString*)fontName fontSize:(NSInteger)fsize textWidth:(CGFloat)width{
    if (!s || s.length <= 0) {
        return 0;
    }
    
    UIFont *font = [UIFont fontWithName:fontName size:fsize];
    CGSize constraint = CGSizeMake(width, CGFLOAT_MAX);
    
    CGSize size = CGSizeZero;
    NSDictionary *attribute = @{NSFontAttributeName:font};
    size = [s boundingRectWithSize:constraint options: NSStringDrawingTruncatesLastVisibleLine | NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:attribute context:nil].size;
    
    return ceil(size.height);
}

+ (CGFloat)textWidth:(NSString *)s fontName:(NSString*)fontName fontSize:(NSInteger)fsize textHeight:(CGFloat)height{
    if (!s || s.length <= 0) {
        return 0;
    }
    
    UIFont *font = [UIFont fontWithName:fontName size:fsize];
    CGSize constraint = CGSizeMake(CGFLOAT_MAX, height);
    CGSize size = CGSizeZero;
    NSDictionary *attribute = @{NSFontAttributeName:font};
    size = [s boundingRectWithSize:constraint options: NSStringDrawingTruncatesLastVisibleLine | NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:attribute context:nil].size;
    
    return ceil(size.width);
}

+ (BOOL)hasChinese:(NSString *)str {
    
    for(int i=0; i< [str length];i++){
        
        int a = [str characterAtIndex:i];
        
        if( a > 0x4e00 && a < 0x9fff)
            
        {
            return YES;
            
        }
    }
    
    return NO;
}

+(NSString *)replaceStringWithAsterisk:(NSString *)originalStr startLocation:(NSInteger)startLocation lenght:(NSInteger)lenght{
    
    NSString *newStr = originalStr;
    
    for (int i = 0; i < lenght; i++) {
        
        NSRange range = NSMakeRange(startLocation, 1);
        
        newStr = [newStr stringByReplacingCharactersInRange:range withString:@"*"];
        
        startLocation ++;
        
    }
    
    return newStr;
    
}

@end
